<?php
namespace Macaca\Controller\Admin;


use Macaca;
use Macaca\Module\Admin\User as ModuleAdminUser;
use Macaca\Module\Linker;
use Macaca\Module\Token;
use Macaca\View\Admin as View;
use Monkey\Controller;
use Monkey;

class Login extends Controller {

    /**
     * @var Macaca\Module\Linker
     */
    public $linker;

    /**
     * @param Monkey\App $app
     */
    public function __construct($app) {
        parent::__construct($app);
        $this->linker = new Linker($app);
    }

    /**
     * 登录界面
     */
    public function actionGetView($data = array()) {
        $view = new View\Login($this->app);
        $token = new Token($this->app);
        $data['title'] = 'Macaca 企业建站系统后台登录';
        $data['url_vcode'] = $this->linker->toFix('/vcode');
        $data['url_login'] = $this->linker->toFix('/admin/login');
        $data['token'] = $token->grantToken('login');

        $data += array('uname' => '', 'msg' => '');
        $this->response->setBody($view->render($data));
    }

    /**
     * 登录处理
     */
    public function actionDoLogin() {
        $token = new Token($this->app);
        $moduleUser = new ModuleAdminUser($this->app);
        if (!isset($_SESSION['vcode']) or !isset($_POST['token']) or !$token->checkToken($_POST['token'], 'login')
        ) {
            $data['msg'] = '请正确访问我们的网站！';
        }
        elseif ($_SESSION['vcode'] != strtolower($_POST['vcode'])) {
            $data['msg'] = '请正确输入验证码！';
        }
        elseif (!$moduleUser->login($_POST)) {
            $data['msg'] = '用户名或密码错误！';
        }

        if (isset($data['msg'])) {
            $this->actionGetView($data + $_POST);
        }
        else {
            unset($_SESSION['vcode']);
            //            $this->writeLine('登录成功！');exit;
            $this->redirect($this->linker->toFix('/admin'));
        }
    }

} 